package nacos

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"travel/service/appconfig"
)

type NaCoSs struct {
	Mysql struct {
		User     string `json:"User"`
		Password string `json:"Password"`
		Host     string `json:"Host"`
		Port     string `json:"Port"`
		Database string `json:"Database"`
	} `json:"mysql"`
	Redis struct {
		Addr     string `json:"Addr"`
		Password string `json:"Password"`
		DB       int    `json:"DB"`
	} `json:"redis"`
	Grpc struct {
		Host string `json:"Host"`
		Port int    `json:"Port"`
	} `json:"grpc"`
	Consul struct {
		Name string `json:"Name"`
		Host string `json:"Host"`
		Port int    `json:"Port"`
	} `json:"consul"`
	Es struct {
		Host string `json:"host"`
	} `json:"es"`
	Realname struct {
		SecretId  string `json:"secretId"`
		SecretKey string `json:"secretKey"`
	} `json:"realname"`
}

var Config NaCoSs

func NewNaCos() {
	nac := appconfig.ViperData.NaCos
	clientConfig := constant.ClientConfig{
		NamespaceId:         nac.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      nac.IpAddr,
			ContextPath: "/nacos",
			Port:        8848,
			Scheme:      "http",
		},
	}
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		return
	}
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: nac.DataId,
		Group:  nac.Group,
	})
	err = json.Unmarshal([]byte(content), &Config)
	if err != nil {
		return
	}

	err = client.ListenConfig(vo.ConfigParam{
		DataId: nac.DataId,
		Group:  nac.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})
	err = json.Unmarshal([]byte(content), &Config)
	if err != nil {
		return
	}
}
